package com.clouddot.baipai.ui.fragment.H;

import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;

import com.clouddot.baipai.R;
import com.clouddot.baipai.component.DaggerIEvaluateFragmentComponent;
import com.clouddot.baipai.contract.IEvaluateFragmentContract;
import com.clouddot.baipai.http.entity.response.getAllWeekResponse;
import com.clouddot.baipai.http.entity.response.getEvaluateByDayResponse;
import com.clouddot.baipai.http.entity.response.getEvaluateByWeekResponse;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.module.EvaluateFragmentModule;
import com.clouddot.baipai.ui.activity.H_UMainActivity;
import com.clouddot.baipai.ui.adapter.H_FDayEvaluateAdapter;
import com.clouddot.baipai.ui.adapter.H_FWeekEvaluateAdapter;
import com.clouddot.baipai.ui.adapter.weekAdapter;
import com.clouddot.baipai.ui.adapter.weekdayAdapter;
import com.clouddot.baipai.util.Toast.ToastUtil;
import com.clouddot.baipai.util.viewUtil.ViewAnim;
import com.clouddot.baipai.util.viewUtil.getTimeAndWeatherUtil;

import org.wxy.sdk.base.IBasePresenter;
import org.wxy.sdk.base.impl.BaseFragment;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Created by wxy on 2018/8/23.
 * 横版班牌评价的主页面
 */

public class H_EvaluateFrgment extends BaseFragment implements IEvaluateFragmentContract.IView {

    private ArrayList<getEvaluateByDayResponse> mDataList = new ArrayList<>();
    private ArrayList<getEvaluateByWeekResponse> mDataLists = new ArrayList<>();
    private H_FDayEvaluateAdapter adapter;
    private H_FWeekEvaluateAdapter adapter1;
    private List<getAllWeekResponse.week> WeekRecordList = new ArrayList<>();
    private List<getTimeAndWeatherUtil.weekday> stringList = new ArrayList<>();

    @Inject
    IEvaluateFragmentContract.IPresenter mPresenter;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.leftLoading)
    ImageView leftLoading;
    @BindView(R.id.loadingLP)
    RelativeLayout loadingLP;
    @BindView(R.id.no)
    ImageView no;
    @BindView(R.id.sp_week)
    Spinner sp_week;
    @BindView(R.id.sp_weekday)
    Spinner sp_weekday;

    private int selectweekIndex;
    private int selectweekDayIndex;
    private String selectStartDataText;
    private String StartDataText;
    private String EndDataText;

    private weekAdapter weekAdapter;
    private weekdayAdapter weekdayAdapter;
    @Override
    public IBasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    protected View inflateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState) {
        return inflater.inflate(R.layout.h_fragment_evaluate, null);
    }

    @Override
    protected void initViews() {
        DaggerIEvaluateFragmentComponent.builder().evaluateFragmentModule(new EvaluateFragmentModule(this)).build().inject(this);
        mPresenter.getAllWeek();
    }

    @Override
    protected void initVariables() {
        Animation loadingAnim = ViewAnim.getRotateImg(getActivity());
        leftLoading.startAnimation(loadingAnim);
        recyclerView.addOnScrollListener(H_UMainActivity.listener);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    @OnClick()
    public void onClick(View view) {
        H_UMainActivity.backTime = Env.getAppContext().backToMainTime * 60;

    }

    @Override
    protected void loadData() {
    }

    /**
     * fragment 隐藏和显现触发的方法，第一次生成的时候不会触发。
     *  hidden 为 false --> 显现 ；为 true --> 隐藏
     * @param hidden
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            loadingLP.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
            no.setVisibility(View.GONE);
            mPresenter.getAllWeek();
        }
    }


    /**
     *
     * @param flag 1 --> 获取某个日期的评价
     *             2 --> 获取全部学期周
     *             3 --> 获取整周的评价
     * @param object
     */
    @Override
    public void success(final int flag, Object object) {
        if(flag == 1){
            ArrayList<getEvaluateByDayResponse> response = (ArrayList<getEvaluateByDayResponse>) object;
            if(response.isEmpty()){
                fail(1,"这个日期没有评价");
                return;
            }
            mDataList = response;
            adapter = new H_FDayEvaluateAdapter(getActivity(),mDataList);
            recyclerView.setAdapter(adapter);
            no.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
            loadingLP.setVisibility(View.GONE);

        }else if (flag == 2) {
            final getAllWeekResponse response = (getAllWeekResponse) object;
            if (response.WeekRecordList.isEmpty()) {
                fail(1,"获取全部周期失败");

                return;
            }
            weekAdapter = new weekAdapter(getActivity());
            WeekRecordList = response.WeekRecordList;
            weekAdapter.setDatas(response.WeekRecordList);

            selectweekIndex = Integer.parseInt(response.CurrentWeek.SerialNo)-2;
            StartDataText = response.CurrentWeek.BeginDateText;
            EndDataText = response.CurrentWeek.EndDateText;
            sp_week.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    try {
                        Field field = AdapterView.class.getDeclaredField("mOldSelectedPosition");
                        field.setAccessible(true);
                        field.setInt(sp_week, AdapterView.INVALID_POSITION);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    selectweekIndex =  Integer.parseInt(WeekRecordList.get(position).SerialNo) - 1;
                    StartDataText = WeekRecordList.get(position).BeginDateText;
                    EndDataText = WeekRecordList.get(position).EndDateText;
                    mPresenter.getEvaluateByWeek("Class",Env.getAppContext().ClassID,WeekRecordList.get(position).Id);
                    refulesDate();
                    loadingLP.setVisibility(View.VISIBLE);
                    recyclerView.setVisibility(View.GONE);
                    no.setVisibility(View.GONE);
                }
                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
            sp_week.setAdapter(weekAdapter);
            sp_week.setSelection(selectweekIndex);
            refulesDate();

        }else if(flag == 3){
            ArrayList<getEvaluateByWeekResponse> response = (ArrayList<getEvaluateByWeekResponse>) object;
            if(response.isEmpty()){
                fail(1,"这周还没有评价");
                return;
            }
            mDataLists = response;
            adapter1 = new H_FWeekEvaluateAdapter(getActivity(),mDataLists);
            recyclerView.setAdapter(adapter1);
            recyclerView.setVisibility(View.VISIBLE);
            loadingLP.setVisibility(View.GONE);
            no.setVisibility(View.GONE);

        }
    }

    @Override
    public void fail(int flag, String errMsg) {
        no.setVisibility(View.VISIBLE);
        recyclerView.setVisibility(View.GONE);
        loadingLP.setVisibility(View.GONE);
        ToastUtil.showToast(getActivity(), errMsg);
    }

    private void refulesDate(){
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        try {
            stringList = getTimeAndWeatherUtil.getWeekData(simpleDateFormat.parse(StartDataText),EndDataText);
            weekdayAdapter = new weekdayAdapter(getActivity());
            weekdayAdapter.setDatas(stringList);
//            for (getTimeAndWeatherUtil.weekday weekday : stringList){
//                if(weekday.weekName.equals(getTimeAndWeatherUtil.getData())){
//                    selectweekDayIndex = weekday.index;
//                    selectStartDataText = weekday.weekName;
//                    break;
//                }
//            }
            sp_weekday.setAdapter(weekdayAdapter);

            sp_weekday.setSelection(0,true);

            sp_weekday.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    if(position == 0){
                        return;
                    }else {
                        try {
                            Field field = AdapterView.class.getDeclaredField("mOldSelectedPosition");
                            field.setAccessible(true);
                            field.setInt(sp_weekday, AdapterView.INVALID_POSITION);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        selectStartDataText = stringList.get(position).weekName;
                        selectweekDayIndex = stringList.get(position).index;
                        mPresenter.getEvaluateByDay("Class", Env.getAppContext().ClassID, selectStartDataText);
                        loadingLP.setVisibility(View.VISIBLE);
                        recyclerView.setVisibility(View.GONE);
                        no.setVisibility(View.GONE);
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
            no.setVisibility(View.GONE);

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }


}
